import { color, Color, lerp, v4 } from 'cc';
import { MeshRenderer } from 'cc';
import { _decorator, Component } from 'cc';
const { ccclass, property, executeInEditMode } = _decorator;

@ccclass('MainColorLerp')
@executeInEditMode
export class MainColorLerp extends Component {

    @property
    private _ratio: number = 0;
    @property({ slide: true, range: [0, 1, .01] })
    public get ratio(): number { return this._ratio; }
    public set ratio(v: number) { this._ratio = v; this.refresh(v); }

    @property
    color0: Color = color();

    @property
    color1: Color = color();

    @property
    materialInstance = true;

    refresh(value) {
        this.getComponentsInChildren(MeshRenderer).forEach(_ => {
            const material = this.materialInstance ? _.getMaterialInstance(0) : _.getMaterial(0);
            let r = lerp(this.color0.r / 255, this.color1.r / 255, value);
            let g = lerp(this.color0.g / 255, this.color1.g / 255, value);
            let b = lerp(this.color0.b / 255, this.color1.b / 255, value);
            let a = lerp(this.color0.a / 255, this.color1.a / 255, value);
            material.setProperty('mainColor', v4(r, g, b, a));
        });
    }

}